package com.sba.core.web.controller;

import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.sba.core.domain.Menu;
import com.sba.core.domain.User;
import com.sba.core.service.MenuService;
import com.sba.core.service.UserService;
import com.sba.core.util.CaptchaUtil;
import com.sba.core.util.HashUtil;
import com.sba.core.util.StringUtil;

/**
 * 
 * @author feiliming
 *
 */
@Controller
@RequestMapping("${ssh.admin-path}")
public class AdminController extends BaseController{
	
	@Autowired
	private MenuService menuService;
	@Autowired
	private UserService userService;

	@GetMapping
	public String index(Map<String, Object> model){
		//List<Menu> menus = menuService.getMenus(0L, true);
		//User user = (User)request.getSession().getAttribute("user");
		
		if(request.getSession().getAttribute("user") != null){
			User user = (User)request.getSession().getAttribute("user");
			Set<Menu> menusByUserId = userService.getMenusByUserId(user.getId());
			//构建成metisMenu需要的结构, 以后改一下
			List<Menu> menus = new ArrayList<Menu>();
			for(Menu m : menusByUserId){
				if(m.getParentId() == 0){
					List<Menu> subMenus = new ArrayList<Menu>();
					for(Menu m2 : menusByUserId){
						if(m2.getParentId() == m.getId()){
							subMenus.add(m2);
						}
					}
					m.setSubMenus(subMenus);
					menus.add(m);
				}
			}
			model.put("menus", menus);
		}
		return adminThemePath + "/index";
	}
	
	@GetMapping("/login")
	public String login(Map<String, Object> model){
		if(request.getSession().getAttribute("user") != null){
			return adminThemePath + "/index";
		}
		model.put("adminPath", adminPath);
		model.put("adminThemePath", adminThemePath);
		return adminThemePath + "/login";
	}
	
	@GetMapping("/dashboard")
	public String dashboard(Map<String, Object> model){
		return adminThemePath + "/dashboard";
	}
	
	@GetMapping("/captcha")
	public @ResponseBody void getCatpcha(String captchaName){
		BufferedImage image = new BufferedImage(CaptchaUtil.WIDTH, CaptchaUtil.HEIGHT, BufferedImage.TYPE_INT_RGB);
		String vCode = CaptchaUtil.drawGraphic(image);
		vCode = vCode.toUpperCase();
		vCode = HashUtil.md5(vCode);
		
		setCookie(captchaName, vCode, -1, "/", true);
		response.setHeader("Pragma","no-cache");
		response.setHeader("Cache-Control","no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");

		ServletOutputStream sos = null;
		try {
			sos = response.getOutputStream();
			ImageIO.write(image, "jpeg", sos);
		}catch (Exception e) {
			
		}finally{
			if (sos != null) {
				try {sos.close();} catch (Exception e) {}
			}
		}
	}
	
	@RequestMapping(path = "/doLogin", method = RequestMethod.POST)
	public @ResponseBody JSONObject doLogin(String loginName, String password, String loginCaptcha, String captchaName){
		boolean r = true; //TODO false 去掉验证码
		String msg = "验证码错误！";
		if(StringUtil.isNotBlank(loginCaptcha) && StringUtil.isNotBlank(captchaName)){
			String kmd5 = HashUtil.md5(loginCaptcha.toUpperCase());
			r = kmd5.equals(getCookie(captchaName));
		}
		User user = null;
		if(r){
			List<User> dlist = userService.getByLoginNameAndIsDisabled(loginName, 1);
			if(dlist.size() > 0){
				r = false;
				msg = "该用户被禁用！";
			}else{
				List<User> plist = userService.getByLoginNameAndPassword(loginName, HashUtil.md5(password));
				if(plist.size() > 0){
					user = plist.get(0);
					r = true;
				}else{
					r = false;
					msg = "用户名或密码错误！";
				}
			}
		}
		if(r){
			request.getSession().setAttribute("user", user);
		}
		
		JSONObject obj = new JSONObject();
		obj.put("success", r);
		obj.put("msg", msg);
		return obj;
	}
	
	@GetMapping("/logout")
	public String logout(Map<String, Object> model){
		request.getSession().removeAttribute("user");
		return "redirect:" + adminPath + "/login";
	}
	
}
